import axios from "axios";
import { Notification, MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken, removeToken } from "@/utils/auth";
import errorCode from "@/utils/errorCode";

//axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
axios.defaults.withCredentials = false;
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分  //
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 60000,
  withCredentials: false, // 不携带cookie
  maxRedirects: 0,
});
// request拦截器
service.interceptors.request.use(
  (config) => {
    config.withCredentials = false;

    // 是否需要设置 token
    // const isToken = (config.headers || {}).isToken === false
    //config.headers['authorization'] = 'bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJtal9hZG1pbl90ZXN0Iiwic2NvcGUiOlsiYWxsIl0sImRlcHRJZCI6IjEyMDMwOCIsImV4cCI6MTczNzQ1MTAyMywidXNlcklkIjo0MywiYXV0aG9yaXRpZXMiOlsiU0pfTUoiLCJBRE1JTiJdLCJqdGkiOiI5ZDMwMzBmNC01YTBhLTQ3YjgtYTM3Ni04ODYzYWExYmVmODUiLCJjbGllbnRfaWQiOiJzeXN0ZW0tYWRtaW4td2ViIiwidXNlcm5hbWUiOiJtal9hZG1pbl90ZXN0In0.X9FC3Kf47fQxHOS3oF936BpCBABjTPWo3zyPDNbw46fokp6nKrgNMxKIA2V5mvfFWaizIF8B9lsoDPTijOi2OanlW089dG2qiNItxinegughxJgcgQwRvEYetV9egd4bycqgdv24dCQeU0c0Bz4-_BVfRiL5AziXlq3Tv-EXhPYnJS3AgyT3zefw1K0HEWsXDNkGIkE__xi-J7_AZCHJQQJA63vJZeZ65HRh4_kV5IF-1lBUJlogI5_Ft8We6q4RfE1T4eGgCDp_jpW4iS3qlHLsbyBdVx62hZMsKGR4u7RQoA-3VhvqROh8_pWc76-CfYeI9as2ncWlRlQutD6KUw';
    //alert(getToken('hezuoMJXT'));
    let v = getToken("hezuoMJXT");
    if (undefined != v && v !== null) {
      config.headers["authorization"] = v; // 让每个请求携带自定义token 请根据实际情况自行修改
    }

    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    const code = res.data.code || 200;
    // 获取错误信息
    const message = errorCode[code] || res.data.msg || errorCode["default"];
    if (code === 401) {
      MessageBox.confirm(
        "登录状态已过期，您可以继续留在该页面，或者重新登录",
        "系统提示",
        {
          confirmButtonText: "重新登录",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        store.dispatch("LogOut").then(() => {
          location.reload();
          removeToken("hezuoMJXT");
        });
      });
    } else if (code === 500) {
      Message({
        message: message,
        type: "error",
      });
      return Promise.reject(new Error(message));
    } else if (code < 100) {
      return res.data;
    } else if (code !== 200) {
      Notification.error({
        title: message,
      });
      return Promise.reject("error");
    } else {
      return res.data;
    }
  },
  (error) => {
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    // return Promise.reject(error)
    const { status, data } = error.response || {};
    if (status === 401||status == 403) {
      MessageBox.confirm(
        "登录状态已过期，您可以继续留在该页面，或者重新登录",
        "系统提示",
        {
          confirmButtonText: "重新登录",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        store.dispatch("LogOut").then(() => {
          location.reload();
          removeToken("hezuoMJXT");
        });
      });
    } else if (status === 500) {
      Message({
        message: data,
        type: "error",
      });
      return Promise.reject(new Error(data));
    } else if (status < 100) {
      return res.data;
    } else if (status !== 200) {
      // Notification.error({
      //   title: data,
      // });
      return Promise.reject("error");
    } else {
      return res.data;
    }
  }
);

export default service;
